package com.pangda.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pangda.common.domain.PageResult;
import com.pangda.common.domain.ResponseResult;
import com.pangda.common.utils.JwtUtil;
import com.pangda.common.utils.UserContext;
import com.pangda.mapper.SysRoleMapper;
import com.pangda.pojo.SysRole;
import com.pangda.pojo.SysUser;
import com.pangda.mapper.SysUserMapper;
import com.pangda.pojo.SysUserRole;
import com.pangda.pojo.Transfer;
import com.pangda.pojo.dto.SysUserDto;
import com.pangda.pojo.vo.SysUserVo;
import com.pangda.service.ISysRoleService;
import com.pangda.service.ISysUserRoleService;
import com.pangda.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xjy
 * @since 2024-06-21
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${huike.framework.jwt.ttl}")
    private Long ttl;
    @Value("${huike.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;

    @Override
    @Transactional
    public ResponseResult addUser(SysUserDto sysUserDto) {
        SysUser bean = BeanUtil.toBean(sysUserDto, SysUser.class);
        save(bean);
        if (ObjectUtil.isNotEmpty(sysUserDto.getRoleIds())) {
            Integer[] roleIds = sysUserDto.getRoleIds();
            List<SysUserRole> collect = Arrays.stream(roleIds).map(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(bean.getUserId());
                sysUserRole.setRoleId(roleId);
                return sysUserRole;
            }).collect(Collectors.toList());
            sysUserRoleService.saveBatch(collect);
        }
        return ResponseResult.success();
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @Override
    public PageResult<SysUserVo> searchUserList(PageResult pageResult, SysUserDto sysUserDto) {
        Page<SysUser> page = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        String beginTime = null;
        String endTime = null;
        if (ObjectUtil.isNotEmpty(pageResult.getParams())) {
            beginTime = (String) pageResult.getParams().get("beginTime");
            endTime = (String) pageResult.getParams().get("endTime");
        }
        sysUserMapper.searchUserList(page, sysUserDto, beginTime, endTime);
        return PageResult.success(page, SysUserVo.class);
    }

    /**
     * 获取用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getUser(Integer userId) {
        SysUserVo userVo = sysUserMapper.getUser(Long.valueOf(userId));
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId), SysUserRole::getUserId, userId);
        List<SysUserRole> list = sysUserRoleService.list(queryWrapper);
        List<Integer> collect = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("data", userVo);
        map.put("msg", "success");
        map.put("roleIds", ArrayUtil.toArray(collect, Integer.class));
        List<SysRole> roles = sysRoleService.list();
        map.put("roles", roles);
        return map;
    }

    /**
     * 修改用户
     *
     * @param sysUserDto
     * @return
     */
    @Override
    public ResponseResult updateUser(SysUserDto sysUserDto) {
        //更新用户信息
        sysUserDto.setUpdateBy(UserContext.getUser());
        sysUserDto.setUpdateTime(String.valueOf(LocalDateTime.now()));
        updateById(BeanUtil.toBean(sysUserDto, SysUser.class));
        //删除旧的用户角色关系
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, sysUserDto.getUserId());
        sysUserRoleService.remove(queryWrapper);
        //添加新的用户角色关系
        if (ArrayUtil.isNotEmpty(sysUserDto.getRoleIds())) {
            Integer[] roleIds = sysUserDto.getRoleIds();
            List<SysUserRole> collect = Arrays.stream(roleIds).map(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUserDto.getUserId());
                sysUserRole.setRoleId(roleId);
                return sysUserRole;
            }).collect(Collectors.toList());
            sysUserRoleService.saveBatch(collect);
        }
        return ResponseResult.success();
    }

    /**
     * 登录
     *
     * @return
     */
    @Override
    public ResponseResult login(Map<String, Object> map) throws ScriptException {
        if (ObjectUtil.isEmpty(map)) {
            return ResponseResult.error();
        }
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String uuid = (String) map.get("uuid");
        String code = (String) map.get("code");
        if (ObjectUtil.isEmpty(username)) {
            return ResponseResult.error("用户名不能为空");
        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, username);
        SysUser one = getOne(queryWrapper);
        if (ObjectUtil.isEmpty(one)) {
            return ResponseResult.error("用户名不存在");
        }
        if (!one.getPassword().equals(password)) {
            return ResponseResult.error("密码错误");
        }
        String o = (String) redisTemplate.opsForValue().get(uuid);
        if (ObjectUtil.isEmpty(o)) {
            return ResponseResult.error("验证码已失效");
        }
        String substring = o.substring(0, o.length() - 1);
        // 创建ScriptEngineManager实例
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine javascript = manager.getEngineByName("javascript");
        Integer eval = (Integer) javascript.eval(substring);
        if (Integer.parseInt(code) != eval) {
            // 验证码错误
            return ResponseResult.error("验证码错误");
        }
        redisTemplate.delete(uuid);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("userId", one.getUserId());
        map1.put("userName", one.getUserName());
        String token = JwtUtil.createJWT(secretKey, Math.toIntExact(ttl), map1);
        UserContext.setUser(username);
        ResponseResult success = ResponseResult.success();
        success.setToken(token);
        return success;
    }

}
